var React = require('react-native');
var {msg} = require('iflux-native');
var webapi = require('./webapi');
var Loading = require('../loading');
var Header = require('../header');

var {
  TouchableOpacity,
  ListView,
  InteractionManager,
  View,
  StyleSheet,
  PixelRatio,
  Text,
  Image,
} = React;


/**
 * 省市区级联选择组件
 *
 * 之前的实现使用了PickerIOS来作为选择的方式，但是这种方式并不能保证在android上的体验
 * 因此，我们重新使用ListView来实现
 */
class Region extends React.Component {
  constructor(props) {
    super(props);
    this._cache = [];
    this._chosen = {};
    this.state = {
      /*是不是结束loading*/
      isEndLoading: false,
      /*listview的数据源*/
      dataSource: new ListView.DataSource({
        rowHasChanged(r1, r2) {
          return r1 != r2;
        }
      })
    };
  }


  /**
   * async/await好用到想哭
   */
  componentDidMount() {
    InteractionManager.runAfterInteractions(async () => {
      try {
        var data = await webapi.fetchRegionData();
        this._data = data;
        //过滤省
        var province = this._filter('086');
        this._cache.push(province);
      } catch(err) {
        if (err) {
          if (__DEV__) {
            console.log('获取省市区数据错误:', err);
            msg.emit('app:tip', '获取省市区错误');
          }
        }
      } finally {
        this.setState({
          isEndLoading: true
        });
      }
    });
  }


  render() {
    var title = ['返回', '选择省', '选择市', '选择区'];

    // 如果当前的状态还是loading状态显示loading组件
    if (!this.state.isEndLoading) {
      return <Loading/>
    }

    return (
      <View style={{flex: 1}}>
        <Header
          leftTitle={title[this._cache.length]}
          onLeftMenuPress={this._handleBackPrevious.bind(this)}/>
        <ListView
            style={{backgroundColor: '#FFF', flex: 1, marginBottom: 10}}
            initialListSize={20}
            renderRow={this._renderRow.bind(this)}
            dataSource={this.getDataSource()}
            showsVerticalScrollIndicator={true}
            automaticallyAdjustContentInsets={false}
        />
      </View>
    );
  }


  /**
   * 获取数据源
   */
  getDataSource() {
    var last = this._cache[this._cache.length - 1];
    return this.state.dataSource.cloneWithRows(last);
  }


  /**
   * render each row
   */
  _renderRow(row) {
    var isArea = this._cache.length === 3;
    var isNoChildren = ['710000', '810000', '820000'].indexOf(row['id']) != -1;
    //如果已经在区，不显示右边的箭头
    return (
      <TouchableOpacity
        key={row['id']}
        style={styles.listRow}
        onPress={this._handleOnPress.bind(this, row['id'], row['name'])}>
        <Text style={styles.text}>{row['name']}</Text>
        {isArea || isNoChildren ?  null : <Image style={styles.image} source={require('img/right.png')}/>}
      </TouchableOpacity>
    );
  }


  /**
   * 处理点击事件
   */
  _handleOnPress(id, name) {
    //点击省的时候先把过去的数据清空一次
    if (this._cache.length === 1) {
      this._chosen = {
        province: id,
        provinceName: name,
        city: '',
        cityName: '',
        area: '',
        areaName: ''
      }
    } else if (this._cache.length === 2) {
      this._chosen['city'] = id;
      this._chosen['cityName'] = name;
    } else if (this._cache.length === 3) {
      this._chosen['area'] = id;
      this._chosen['areaName'] = name;
    }

    var children = this._filter(id);
    //已经没有子节点
    if (children.length === 0) {
      this.props.onSubmit && this.props.onSubmit(this._chosen);
      return;
    }
    this._cache.push(children);
    this.forceUpdate();
  }


  /**
   * 处理返回上一级
   */
  _handleBackPrevious() {
    if (this._cache.length > 1) {
      this._cache.pop();
      this.forceUpdate();
    } else {
      this.props.onCancel && this.props.onCancel();
    }
  }


  /**
   * 根据pid查询子节点
   */
  _filter(pid) {
    var result = [];

    for (var code in this._data) {
      if (this._data.hasOwnProperty(code)
          && this._data[code][1] === pid) {
        result.push({
          id: code,
          name: this._data[code][0]
        });
      }
    }

    return result;
  }
}


var styles = StyleSheet.create({
  listRow: {
    backgroundColor: '#FFF',
    flexDirection: 'row',
    height: 50,
    padding: 10,
    alignItems: 'center',
    justifyContent: 'space-between',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  nav: {
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 50,
    backgroundColor: '#3d85cc',
    flexDirection: 'row'
  },
  navText: {
    color: '#FFF',
    fontSize: 16
  },
  btn: {
    padding: 15,
  },
  text: {
    fontSize: 14,
  },
  image: {
    height: 15,
    width: 8
  }
});


module.exports = Region;
